package edu.nctu.csie.jichang.spring;

import java.io.File;

import org.springframework.beans.factory.config.PropertyOverrideConfigurer;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.ResourceLoader;

public class EnhanceLocation extends PropertyOverrideConfigurer implements ResourceLoaderAware {
	
	private String fileName;
	private ResourceLoader loader;
	
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	private void initLocation() {
		try {
			if ( loader!=null && fileName != null && fileName.length()>0 &&  loader instanceof EnhanceFileSystemXmlApplicationContext) {
				EnhanceFileSystemXmlApplicationContext tFileSystem = (EnhanceFileSystemXmlApplicationContext)loader ;
//				Method tMethod = AbstractRefreshableConfigApplicationContext.class.getDeclaredMethod("getConfigLocations");
//				tMethod.setAccessible(true);
//				Object tReturnValue = tMethod.invoke(tFileSystem);
//				if (tReturnValue instanceof String[]) {
				String[] tValues = tFileSystem.getConfigLocations();
				if(tValues.length >0){
					if(tValues[0] != null && tValues[0].length() > 0){
						File tPath = new File(tValues[0]);
						if(tPath.exists()){
							File tFile = new File(tPath.getParent()+"\\"+fileName);
							if(tFile.exists()){
								System.out.println("Load override property file = " + tFile.getAbsolutePath());
								setLocation(new FileSystemResource(tFile));
							}else{
								System.out.println("Can't find override property file = " + tFile.getAbsolutePath());
							}
						}else{
							System.out.println("Can't find ienc.xml file = " + tPath.getAbsolutePath());
						}
					}
				}
			}
		} catch (Exception e) {
			System.err.println(e);
		}
	}

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		loader = resourceLoader;
		initLocation();
	}

}